package com.whitehot.klib.engine;

import com.google.gson.Gson;
import com.whitehot.klib.engine.bean.Ipinfo;
import com.whitehot.klib.engine.bean.IpinfoResp;
import com.whitehot.klib.engine.bean.TmpInfo;
import com.whitehot.klib.http.net.InnerHttpManager;
import com.whitehot.klib.http.net.ResultCallback;

/**
 * Created by ytf on 2018/5/20 020.
 * Description:  获取外网ip
 */

public class IpInfoGetter
{
    private InnerHttpManager manager;

    public IpInfoGetter()
    {
        manager = InnerHttpManager.getInstance();
    }

    public void get(final Callback callback)
    {
        manager.doGet("http://ip.taobao.com/service/getIpInfo.php?ip=myip",
                new ResultCallback<IpinfoResp>()
        {
            @Override
            public void onError(String simpleMsg, int code, Exception e)
            {
                get2(callback);
            }

            @Override
            public void onSuccess(IpinfoResp response)
            {
                if(callback != null)
                {
                    callback.onInfo(response.data);
                }
            }
        });
    }

    private void get2(final Callback callback)
    {
        manager.doGet("http://pv.sohu.com/cityjson?ie=utf-8",
                new ResultCallback<String>()
        {
            @Override
            public void onError(String simpleMsg, int code, Exception e)
            {
                if(callback != null)
                {
                    callback.onInfo(Ipinfo.buildEmptyInfo());
                }
            }

            @Override
            public void onSuccess(String response)
            {
                if(callback != null)
                {
                    callback.onInfo(buildFromString(response));
                }
            }
        });
    }

    private Ipinfo buildFromString(String s)
    {
//        var returnCitySN = {"cip": "118.249.101.33", "cid": "430100", "cname": "湖南省长沙市"};

        try
        {
            int start = s.indexOf("{");
            int end = s.lastIndexOf("}");
            if(start > 0 && end > 0)
            {
                String gson = s.substring(start, end + 1);
                Gson g = new Gson();
                TmpInfo d = g.fromJson(gson, TmpInfo.class);
                Ipinfo ip = new Ipinfo();
                ip.ip = d.cip;
                ip.region_id = d.cid;
                ip.region = d.cname;
                ip.city = d.cname;
                return ip;
            }
        }catch (Exception e)
        {
            return new Ipinfo();
        }
        return new Ipinfo();
    }

    public interface Callback
    {
        void onInfo(Ipinfo data);
    }
}
